﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XTYAPI.通讯
{
  public  class UDPServer
    {
        private Socket udpServer;

        public List<Socket> SocketList { get; private set; } = new List<Socket>();
        private CancellationTokenSource cts = new CancellationTokenSource();

        public event Action<Socket> Recive;
        public bool StartListen(string ip, int port)
        {
            udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp);
            udpServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 2000);
            udpServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 2000);
            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            try
            {
                udpServer.Bind(iPEndPoint);
             
                Task.Run(() =>
                {
                    ListenMessage();
                }, cts.Token);
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return true;
        }

        private void ListenMessage()
        {
            while (!cts.IsCancellationRequested)
            {
                EndPoint ep = new IPEndPoint(IPAddress.Any, 0);

                byte[] buffer = new byte[1024 * 2];

                int length = -1;

                try
                {
                    length = udpServer.ReceiveFrom(buffer, ref ep);

                    string message = Encoding.Default.GetString(buffer, 0, length);

                    //AddLog(0, "接收消息：" + message);

                }
                catch (Exception)
                {
                    break;
                }

            }
        }
        private void ReceiveFrom(Socket udpClient)
        {
            while (true)
            {
                byte[] buffer = new byte[1024];
                int length = -1;
                EndPoint  endPoint =new IPEndPoint(IPAddress.Any, 0);
                try
                {
                    length = udpClient.ReceiveFrom(buffer,ref endPoint);
                }
                catch (Exception)
                {
                    //写入日志
                    break;
                }
                if (length > 0)
                {
                    Recive?.Invoke(udpClient);
                }
            }
        }
    }
}
